﻿using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Configuration;
using System.Diagnostics;
using System.Media;
using System.Threading;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Forms;
using System.Windows.Interop;

namespace AutoClick
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : WindowX
    {
        //全局变量
        public static bool isRead = true;
        public static bool isSound = false;
        //播放
        public SoundPlayer player = new SoundPlayer();
        //热键监听
        readonly Dictionary<string, short> hotKeyDic = new Dictionary<string, short>();
        public IntPtr wpfHwnd;
        //界面按键
        private ObservableCollection<Buttons> _buttonsList;
        private ObservableCollection<Buttons> _cbList;
        public List<Buttons> lvBList = new List<Buttons>();
        private short sid;
        string[] lvbuttons = ConfigurationManager.AppSettings["lvButtons"].Split(';');
        string[] lvbuttonsBnk = ConfigurationManager.AppSettings["lvButtonsBnk"].Split(';');
        List<Buttons> list1 = new List<Buttons>();
        
        public static Buttons StartKey = null;
        public static int space = 100;
        Buttons EndButtons = new Buttons { ButtonName = ConfigHelper.GetAppConfig("cbStart") };
        Buttons StartButtons = new Buttons { ButtonName = ConfigHelper.GetAppConfig("cbEnd") };
        public ObservableCollection<Buttons> ButtonsList
        {
            get
            {
                if (_buttonsList == null)
                {
                    _buttonsList = new ObservableCollection<Buttons>();
                }
                return _buttonsList;
            }
        }

        public ObservableCollection<Buttons> CbList
        {
            get
            {
                if (_cbList == null)
                {
                    _cbList = new ObservableCollection<Buttons>();
                }
                return _cbList;
            }
        }


        //实例化notifyIOC控件最小化托盘
        private NotifyIcon notifyIcon = new NotifyIcon();


        public MainWindow()
        {

            InitializeComponent();

            initialTray();


            string[] buttonName = new string[] { "Q", "E", "R", "T", "Y", "U", "I", "O", "P", "F", "G", "H", "J", "K", "L", "Z", "X", "C", "V", "B", "N", "M", "1", "2" };


            lvBList.Clear();
            for (int i = 0; i < lvbuttons.Length; i++)
            {

                if (lvbuttonsBnk[i] == "0" && !lvbuttons[i].IsNullOrEmpty()) { lvBList.Add(new Buttons { ButtonName = lvbuttons[i], Bnk = false }); }

                else if (!lvbuttons[i].IsNullOrEmpty()) { lvBList.Add(new Buttons { ButtonName = lvbuttons[i], Bnk = true }); }

            }
            foreach (string str in buttonName)
            {
                list1.Add(new Buttons { ButtonName = str });
            }


            ButtonsList.Clear();
            CbList.Clear();
            foreach (Buttons item in lvBList)
            {
                ButtonsList.Add(item);
            }

            foreach (Buttons item in list1)
            {
                CbList.Add(item);
            }



            lv.ItemsSource = lvBList;
            //设置启动键
            cbStart.ItemsSource = list1;

            //设置结束键
            cbEnd.ItemsSource = list1;

            //设置暂停键
            cbPardon.ItemsSource = list1;

            tbSpace.Text = ConfigHelper.GetAppConfig("space");

        }


        protected override void OnContentRendered(EventArgs e)
        {
            wpfHwnd = new WindowInteropHelper(this).Handle;
            Console.WriteLine(wpfHwnd.ToInt32());
            var hWndSource = HwndSource.FromHwnd(wpfHwnd);
            if (hWndSource != null) hWndSource.AddHook(MainWindowProc);

            lv.SelectedIndex = lvBList.FindIndex(c => c.Bnk == true);
            cbStart.SelectedIndex = list1.FindIndex(b => b.ButtonName == ConfigHelper.GetAppConfig("cbStart"));
            cbEnd.SelectedIndex = list1.FindIndex(b => b.ButtonName == ConfigHelper.GetAppConfig("cbEnd"));
            cbPardon.SelectedIndex = list1.FindIndex(c => c.ButtonName == ConfigHelper.GetAppConfig("cbPardon"));

        }

        //初始化Lvb列表
        public void InitLvBList()
        {
            lvbuttons = ConfigurationManager.AppSettings["lvButtons"].Split(';');
            lvbuttonsBnk = ConfigurationManager.AppSettings["lvButtonsBnk"].Split(';');



            lv.ItemsSource = lvBList;
        }

        // 最小化系统托盘
        private void initialTray()
        {

            //设置托盘的各个属性            
            notifyIcon.BalloonTipText = "AutoClick已启动";//托盘气泡显示内容
            notifyIcon.Text = "AutoClick";
            notifyIcon.Visible = true;//托盘按钮是否可见
            //重要提示：此处的图标图片在resouces文件夹。可是打包后安装发现无法获取路径，导致程序死机。建议复制一份resouces文件到UI层的bin目录下，确保万无一失。
            notifyIcon.Icon = System.Drawing.Icon.ExtractAssociatedIcon(System.Windows.Forms.Application.ExecutablePath);//托盘中显示的图标
            notifyIcon.ShowBalloonTip(1000);//托盘气泡显示时间
            //双击事件
            //_notifyIcon.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseClick);
            //鼠标点击事件
            notifyIcon.MouseClick += new System.Windows.Forms.MouseEventHandler(notifyIcon_MouseClick);
            //右键菜单--退出菜单项
            System.Windows.Forms.MenuItem exit = new System.Windows.Forms.MenuItem("关闭");
            exit.Click += new EventHandler(exit_Click);
            //关联托盘控件
            System.Windows.Forms.MenuItem[] childen = new System.Windows.Forms.MenuItem[] { exit };
            notifyIcon.ContextMenu = new System.Windows.Forms.ContextMenu(childen);
            //窗体状态改变时触发
            this.StateChanged += MainWindow_StateChanged;
        }


        // 托盘图标鼠标单击事件
        private void notifyIcon_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
        {
            //鼠标左键，实现窗体最小化隐藏或显示窗体
            if (e.Button == MouseButtons.Left)
            {
                if (this.Visibility == Visibility.Visible)
                {
                    this.Visibility = Visibility.Hidden;
                    //解决最小化到任务栏可以强行关闭程序的问题。
                    this.ShowInTaskbar = false;//使Form不在任务栏上显示
                }
                else
                {
                    this.Visibility = Visibility.Visible;
                    //解决最小化到任务栏可以强行关闭程序的问题。
                    this.ShowInTaskbar = true;//使Form不在任务栏上显示
                    this.Activate();
                }
            }

        }

        // 窗体状态改变时候触发
        private void SysTray_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                this.Visibility = Visibility.Hidden;
            }
        }


        // 退出选项
        private void exit_Click(object sender, EventArgs e)
        {
            if (System.Windows.MessageBox.Show("确定退出吗?",
                                               "application",
                                                MessageBoxButton.YesNo,
                                                MessageBoxImage.Question,
                                                MessageBoxResult.Yes) == MessageBoxResult.Yes)
            {
                //System.Windows.Application.Current.Shutdown();
                System.Environment.Exit(0);
            }
        }
        //关闭程序托盘图标消失
        protected override void OnClosed(EventArgs e)
        {
            notifyIcon.Visible = false;
            notifyIcon.Dispose();
        }

        // 窗口状态改变，最小化托盘
        private void MainWindow_StateChanged(object sender, EventArgs e)
        {
            if (this.WindowState == WindowState.Minimized)
            {
                this.Visibility = Visibility.Hidden;
            }
        }



        private void Button_Click_Set(object sender, RoutedEventArgs e)
        {
            string templvB = ConfigurationManager.AppSettings["lvButtons"];
            string templvBB = ConfigurationManager.AppSettings["lvButtonsBnk"];
            bool tempbool = true;
            if (tbKey.Text.Trim() != String.Empty)
            {
                foreach (Buttons item in ButtonsList)
                {
                    if (item.ButtonName == tbKey.Text.ToUpper())
                    {
                        tempbool = false;
                    }
                }
                if (tempbool)
                {
                    ButtonsList.Add(new Buttons { ButtonName = tbKey.Text.ToUpper(), Bnk = false });
                    templvB = templvB + tbKey.Text.ToUpper() + ";";
                    templvBB = templvBB + "0" + ";";
                }
                lv.ItemsSource = ButtonsList;
                ConfigHelper.UpdateAppConfig("lvButtons", templvB);
                ConfigHelper.UpdateAppConfig("lvButtonsBnk", templvBB);
            }

        }

        private void Button_Click_Delete(object sender, RoutedEventArgs e)
        {
            string str = "";
            string templvB = "";
            Buttons buttons = lv.SelectedItem as Buttons;
            if (buttons != null)
            {
                for (int i = 0; i < ButtonsList.Count;)
                {
                    if (ButtonsList[i].ButtonName == buttons.ButtonName)
                    {

                        ButtonsList.Remove(ButtonsList[i]);
                    }
                    else
                    {
                        templvB = templvB + ButtonsList[i].ButtonName + ";";
                        str += "0;";
                        i++;
                    }
                }
                lv.ItemsSource = ButtonsList;
                ConfigHelper.UpdateAppConfig("lvButtons", templvB);
                ConfigHelper.UpdateAppConfig("lvButtonsBnk", str);
            }

        }

        private void lv_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string str = "";
            StartKey = lv.SelectedItem as Buttons;
            lv.SelectedItem = StartKey;
            Console.WriteLine(ButtonsList.Count);
            foreach (Buttons buttons in ButtonsList)
            {
                if (buttons == StartKey)
                {
                    str += "1;";
                }
                else
                {
                    str += "0;";
                }
                Console.WriteLine(str);
            }
            ConfigHelper.UpdateAppConfig("lvButtonsBnk", str);
            if (StartKey.IsNull())
            {
                if (hotKeyDic.ContainsKey("cbStart"))
                {
                    Win32.UnregisterHotKey(wpfHwnd, hotKeyDic["cbStart"]);
                    Win32.UnregisterHotKey(wpfHwnd, hotKeyDic["cbEnd"]);
                }
            }
            else
            {

                ADDHotkey(StartButtons, "cbStart");
                ADDHotkey(EndButtons, "cbEnd");
            }
        }

        private void cbStart_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StartButtons = cbStart.SelectedItem as Buttons;
            ConfigHelper.UpdateAppConfig("cbStart", StartButtons.ButtonName);
            Console.WriteLine(StartButtons.ButtonName);

            if (!StartKey.IsNull())
            {
                ADDHotkey(StartButtons, "cbStart");
            }

        }

        private void cbEnd_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            EndButtons = cbEnd.SelectedItem as Buttons;
            ConfigHelper.UpdateAppConfig("cbEnd", EndButtons.ButtonName);

            if (!StartKey.IsNull())
            {
                ADDHotkey(StartButtons, "cbEnd");
            }

        }

        private void cbPardon_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Buttons buttons = cbPardon.SelectedItem as Buttons;
            ConfigHelper.UpdateAppConfig("cbPardon", buttons.ButtonName);

            //ADDHotkey(buttons, "cbPardon");
        }

        private void tbSpace_TextChanged(object sender, TextChangedEventArgs e)
        {
            int.TryParse(tbSpace.Text, out space);
            //if (space < 40)
            //{
            //    System.Windows.MessageBox.Show("按键间隔不能小于40");
            //}
            //else
            //{
            ConfigHelper.UpdateAppConfig("space", tbSpace.Text.Trim());
            //}
        }


        /// <summary>
        /// 响应快捷键事件
        /// </summary>
        /// <param name="hwnd"></param>
        /// <param name="msg"></param>
        /// <param name="wParam"></param>
        /// <param name="lParam"></param>
        /// <param name="handled"></param>
        /// <returns></returns>

        private void ADDHotkey(Buttons buttons, string CB)
        {

            if (hotKeyDic.ContainsKey(CB))
            {
                Win32.UnregisterHotKey(wpfHwnd, hotKeyDic[CB]);
            }
            else
            {
                sid = Win32.GlobalAddAtom(CB);
                hotKeyDic.Add(CB, Win32.GlobalAddAtom(CB));
            }
            if (!StartKey.IsNull())
            {
                Win32.RegisterHotKey(wpfHwnd, hotKeyDic[CB], Win32.KeyModifiers.None, (int)buttons.ButtonName.ToCharArray()[0]);
            }
        }
        private void UnHotkey(string CB)
        {
            if (hotKeyDic.ContainsKey(CB))
            {
                Win32.UnregisterHotKey(wpfHwnd, hotKeyDic[CB]);
            }
        }
        private IntPtr MainWindowProc(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam, ref bool handled)
        {
            Thread t = new Thread(PressKey);
            switch (msg)
            {
                case Win32.WmHotkey:
                    {
                        int sid = wParam.ToInt32();
                        if (sid == hotKeyDic["cbStart"])
                        {
                            Win32.UnregisterHotKey(wpfHwnd, hotKeyDic["cbStart"]);
                            Win32.RegisterHotKey(wpfHwnd, hotKeyDic["cbEnd"], Win32.KeyModifiers.None, (cbEnd.SelectedItem as Buttons).ButtonName.ToCharArray()[0]);

                            if (cbSound.IsChecked.Equals(true))
                            {
                                EndMedia.Stop();
                                StartMedia.Play();
                            }
                            isRead = true;
                            t.Start();

                        }
                        else if (sid == hotKeyDic["cbEnd"])
                        {
                            if (cbSound.IsChecked.Equals(true))
                            {
                                StartMedia.Stop();
                                EndMedia.Play();
                            }
                            isRead = false;
                            Win32.UnregisterHotKey(wpfHwnd, hotKeyDic["cbEnd"]);
                            Win32.RegisterHotKey(wpfHwnd, hotKeyDic["cbStart"], Win32.KeyModifiers.None, (cbStart.SelectedItem as Buttons).ButtonName.ToCharArray()[0]);
                        }

                        handled = true;
                        break;
                    }
            }

            return IntPtr.Zero;
        }


        public static void PressKey()
        {
            while (isRead)
            {
                if (!StartKey.IsNull())
                {
                    DDIO.DD_key(DDIO.DD_todc(StartKey.ButtonName.ToCharArray()[0]), 1);
                    Thread.Sleep(40);
                    DDIO.DD_key(DDIO.DD_todc(StartKey.ButtonName.ToCharArray()[0]), 2);
                }

                Thread.Sleep(space);
                
            }
        }

        private void tbKey_TextChanged(object sender, TextChangedEventArgs e)
        {

        }
        private void Hyperlink_Click(object sender, RoutedEventArgs e)
        {
            Hyperlink link = sender as Hyperlink;
            Process.Start(new ProcessStartInfo(link.NavigateUri.AbsoluteUri));
        }

    }
}


